package control

import (
	"context"
	"fmt"
	"dockerui/models"
	ut "dockerui/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"time"
)

func clientInfo() (models.DockerCliInfo, int, error){
	var (
		containersCount int
		imagesCount int
		networksCount int
		cli *client.Client
		ctx context.Context
		err error
		cancel context.CancelFunc
		dockerCli models.DockerCliInfo
		cliVersion string // 客户端版本
		dockerInfo types.Version // docker信息
		dockerPlatform string // docker platform
		dockerVersion string  // docker version

	)

	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	cli = ut.GClient
	// docker client version
	cliVersion = cli.ClientVersion()

	imagesCount, containersCount, networksCount = dockerItemCount()

	// docker platform version
	// @TODO 检查是否逻辑不严谨
	if dockerInfo, err = cli.ServerVersion(ctx); err != nil {
		fmt.Println("get version error", err)
		return dockerCli, 0, err
	} else {
		dockerPlatform = dockerInfo.Platform.Name
		dockerVersion = dockerInfo.Version
	}
	dockerCli = models.DockerCliInfo{
		CliVersion: cliVersion,
		Platform: dockerPlatform,
		DockerVersion: dockerVersion,
		ImagesCount: imagesCount,
		ContainersCount: containersCount,
		NetworksCount: networksCount,
	}
	return dockerCli, 1, nil
}


func dockerItemCount() (int, int, int){
	/*
		获取docker相关条目的数目
	*/
	var (
		skipDefault int
		limitDefault int
		searchDefault string
		err error
		imagesCount int
		containerCount int
		networksCount int
	)

	skipDefault, limitDefault = 0, 10
	searchDefault = ""
	if _, imagesCount, err = dockerImages(skipDefault, limitDefault,searchDefault); err != nil {
		imagesCount = 0
	}

	if _, containerCount, err = dockerContainer(skipDefault, limitDefault, searchDefault); err != nil {
		containerCount = 0
	}
	if _, networksCount, err = dockerNetworks(skipDefault, limitDefault, searchDefault); err != nil {
		networksCount = 0
	}
	return imagesCount, containerCount, networksCount
}
